package cn.edu.lingnan.fruitshop.service.impl;

import cn.edu.lingnan.fruitshop.common.JSONResult;
import cn.edu.lingnan.fruitshop.mapper.*;
import cn.edu.lingnan.fruitshop.pojo.*;
import cn.edu.lingnan.fruitshop.service.GoodstableService;
import cn.edu.lingnan.fruitshop.vo.SellerComments;
import cn.edu.lingnan.fruitshop.vo.SellerOrder;
import cn.edu.lingnan.fruitshop.vo.SellerOrderDetail;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import java.util.List;
import org.springframework.ui.Model;

import javax.servlet.http.HttpSession;
import java.util.List;
import org.springframework.ui.Model;

import java.util.List;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张小凡
 * @since 2022-01-04
 */
@Service
public class GoodstableServiceImpl extends ServiceImpl<GoodstableMapper, Goodstable> implements GoodstableService {


    @Autowired(required = false)
    private GoodstypeMapper goodstypeMapper;
    @Autowired(required = false)
    private GoodstableMapper goodstableMapper;
    @Autowired(required = false)
    private CommentMapper commentMapper;
    @Autowired(required = false)
    private AddressMapper addressMapper;
    @Autowired(required = false)
    private OrderdetailMapper orderdetailMapper;
    @Autowired(required = false)
    private OrdertableMapper ordertableMapper;
    @Autowired(required = false)
    private BrowseMapper browseMapper;


    /**
     * 搜索
     * @param model
     * @param goodsName
     * @return
     */
    @Override
    public String searchForGoods(Model model,String goodsName) {
        QueryWrapper<Goodstable> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name",goodsName);
        List<Goodstable> fruitsGoodList = goodstableMapper.selectList(queryWrapper);
        model.addAttribute("fruitsGoodList",fruitsGoodList);
        return "user/list";
    }

    private String picturePath = null;

    /**
     * 搜索
     * @param model
     * @return
     */
    @Override
    public String showGoods(Model model) {
        //显示商品分类信息
        QueryWrapper<Goodstype>queryWrapper = new QueryWrapper<>();
        List<Goodstype> goodstypes = goodstypeMapper.selectList(queryWrapper);
        model.addAttribute("goodstypes",goodstypes);

////显示商品信息
//        QueryWrapper<Goodstable> queryWrapper1 = new QueryWrapper<>();
//// 排好序
//        queryWrapper1.orderByAsc("type_id");
//        queryWrapper1.eq("state",1);
//        List<Goodstable> list = goodstableMapper.selectList(queryWrapper1);

// 这里筛选商品，使得每种种类商品最多只有四个
// 记录数量 控制数量
        int a = 0;
// 记录种类
        int t = 0;

        List<Goodstable> list1 = new LinkedList<>();
        for (int i = 0; i < goodstypes.size(); i++) {
            QueryWrapper<Goodstable> wrapper = new QueryWrapper<>();
            wrapper.eq("state",1);
            wrapper.eq("type_id",goodstypes.get(i).getId());
            PageInfo pageInfo = getPageInfo(1, 4, wrapper);
            List list2 = pageInfo.getList();
            for (Object o : list2) {
                list1.add((Goodstable) o);
            }
        }
// 种类默认为第一个的种类
//        t = list.get(0).getTypeId();
//
//        for (Goodstable goodstable : list) {
//            if ( a < 4 ){
//                if (t != goodstable.getTypeId())
//                    a = 0;
//                t = goodstable.getTypeId();
//                list1.add(goodstable);
//                a++;
//            }
//            else {
//                if (t != goodstable.getTypeId())
//                    a = 0;
//            }
//        }

        model.addAttribute("goodstable",list1);
        return "user/index";
    }






    //查询类型为水果的更多页面
    @Override
    public String Seemore(Model model, HttpSession session,Integer typeId) {

        QueryWrapper<Goodstable> queryWrapper10=new QueryWrapper<>();
        queryWrapper10.eq("state",1);
        queryWrapper10.eq("type_id",typeId);
        List<Goodstable> fruitsGoodList=goodstableMapper.selectList(queryWrapper10);
        model.addAttribute("fruitsGoodList",fruitsGoodList);
        System.out.println(fruitsGoodList);


        return "user/list";
    }

    //点击商品出现商品详情

    @Override
    public String goodDetail(Integer goodId, Model model,HttpSession session) {
        //暂时不对参数进行判断
        Goodstable goodstable=goodstableMapper.selectById(goodId);
        System.out.println("goodstable:"+goodstable);
        model.addAttribute("goodstable",goodstable);

        //根据商品id查出商品类型id
        Integer goodstypeId=goodstable.getTypeId();

//        商品类型id，查询对应名称
       Goodstype goodstype =goodstypeMapper.selectById(goodstypeId);

        //获取类型名称
        String typeName=goodstype.getTypeName();
        model.addAttribute("typeName",typeName);
        //        获取评论内容
        QueryWrapper<Comment> queryWrapper11=new QueryWrapper<>();
        queryWrapper11.eq("good_id",goodId);
        System.out.println("食物的id为"+goodId);
        List<Comment> CommentList=commentMapper.selectList(queryWrapper11);
        model.addAttribute("comment",CommentList);
        System.out.println("comment:"+CommentList);
        //点击到商品详情后插入一条浏览记录
        User user = (User) session.getAttribute("user");
        if (user != null) {
            Integer uid = user.getUserId();
            //根据商品的id和uid查询browse表
            QueryWrapper<Browse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("good_id", goodId).eq("user_id", uid);
            Browse browse = browseMapper.selectOne(queryWrapper);
            if (browse != null) {
                browse.setSearchTime(new Date());
                browseMapper.updateById(browse);
            }else {
                Browse browse2 = new Browse().setUserId(uid).setGoodId(goodId).setSearchTime(new Date());
                browseMapper.insert(browse2);
            }
        }


        return "user/detail";
    }

    @Override
    public JSONResult<Void> picture(MultipartFile file) {

        //MultipartFile:可以看作是一个上传上来的文件对象，里面有文件的相关信息，比如文件名
        if(file == null)
        {
            return new JSONResult<>(201,"文件不能为空");
        }
        //获取文件名
        String filename = file.getOriginalFilename();
        // 获取文件最后一个.出现的索引位置
        int i = filename.lastIndexOf(".");
        // 从指定位置开始截取字符串，这里是为了获取文件的格式，然后可以对文件格式进行判断，这里不判断，默认是图片格式
        String substring = filename.substring(i);
        //获取一串32位的随机字符串来作为文件的名字
        String s = UUID.randomUUID().toString();
        //获取文件要保存在类路径下的目录，用于将文件回显时能访问到该文件
        try {
            String path = ResourceUtils.getURL("classpath:static/images").getPath();
            int target = path.lastIndexOf("target");
            String absoultPath = path.substring(0,target)+"src/main/resources/static/images";
            System.out.println("path:"+path);
            File file1 = new File(path);
            if(!file1.exists())
            {
                file1.mkdir();
            }
            String newFileName=s+substring;
            File file2=new File(file1,"/"+newFileName);

            file.transferTo(file2);
            File file3 = new File(file1, "/" + newFileName);
            File file4 = new File(absoultPath + "//" + newFileName);
            FileInputStream inputStream = new FileInputStream(file3);
            FileOutputStream outputStream = new FileOutputStream(file4);
            byte[] bytes = new byte[1024];
            int len = -1;
            while((len=inputStream.read(bytes))!=-1)
            {
                outputStream.write(bytes, 0, len);
            }
            inputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            return new JSONResult<>(201,"文件上传失败");

        } catch (IOException e) {
            return new JSONResult<>(201,"文件上传失败");
        }
        picturePath = s+substring;
        return new JSONResult<>(200,s+substring);
    }

    @Override
    public JSONResult<Void> getPictureUrl() {
        if(picturePath == null)
        {
            return new JSONResult<>(201,"图片不存在");
        }
        return new JSONResult<>(200,picturePath);
    }

    @Override
    public JSONResult<Void> addGoods(String name,String newPrice,
                                     String store,String goodDetail,Integer typeId,HttpSession session) {
        //检查商品名称
        JSONResult<Void> nameResutl = checkName(name);
        if(nameResutl.getCode() != 200)
        {
            return nameResutl;
        }
        //检查商品详情
        JSONResult<Void> goodDetail2 = checkGoodDetail(goodDetail);
        if(goodDetail2.getCode() != 200)
        {
            return goodDetail2;
        }
        //检查商品数量
        JSONResult<Void> goodNum = checkGoodNum(store);
        if(goodNum.getCode() != 200)
        {
            return goodNum;
        }
        //检查商品价格
        JSONResult<Void> goodPrice = checkGoodPrice(newPrice);
        if(goodPrice.getCode() != 200)
        {
            return goodPrice;
        }
        if(picturePath == null)
        {
            return new JSONResult(206,"文件不能为空");
        }
        Goodstable goodstable = new Goodstable();
        goodstable.setName(name);
        goodstable.setOldPrice(Double.parseDouble(newPrice));
        goodstable.setNewPrice(Double.parseDouble(newPrice));
        goodstable.setStore(Integer.parseInt(store));
        goodstable.setPicture(picturePath);
        goodstable.setFlag(2);
        goodstable.setTypeId(typeId);
        goodstable.setCreateTime(new Date());
        goodstable.setState(1);
        goodstable.setGoodDetail(goodDetail);
        User user = (User)session.getAttribute("user");
        if(user == null)
        {
            return new JSONResult<>(206,"请商家先登录");
        }
        //商家id 默认为2，先写死
        goodstable.setBossId(user.getUserId());
        int insert = goodstableMapper.insert(goodstable);
        if(insert != 1)
        {
            return new JSONResult<>(205,"新增失败");
        }
        picturePath = null;
        return new JSONResult<>(200,"新增成功");
    }
    @Override
    public JSONResult<Void> checkName(String goodName) {
        if(goodName == null || goodName.equals(""))
        {
            return new JSONResult<Void>(201,"名称不能为空");
        }
        return new JSONResult<>(200,"OK");
    }

    @Override
    public JSONResult<Void> checkGoodDetail(String goodDetail) {
        if(goodDetail==null || goodDetail.equals(""))
        {
            return  new JSONResult<>(201,"商品详细不能为空");
        }
        return new JSONResult<>(200,"OK");
    }

    @Override
    public JSONResult<Void> checkGoodNum(String goodNum) {
        if(goodNum == null || goodNum.equals(""))
        {
            return new JSONResult<>(201,"数量不能为空");
        }
        try {
            Double num = Double.parseDouble(goodNum);
        } catch (NumberFormatException e) {
            return new JSONResult<>(202,"商品数量要为整数");
        }
        return new JSONResult<>(200,"OK");
    }

    @Override
    public JSONResult<Void> checkGoodPrice(String goodPrice) {
        if(goodPrice == null || goodPrice.equals(""))
        {
            return new JSONResult<>(201,"商品价格不能为空");
        }
        try {
            Double price = Double.parseDouble(goodPrice);
        } catch (NumberFormatException e) {
            return new JSONResult<>(202,"价格要满足浮点数格式");
        }
        return new JSONResult<>(200,"OK");
    }

    @Override
    public String toGoodsInfo(Model model,HttpSession session,Integer pageNum) {
        // 默认商家id为2
        User user =  (User) session.getAttribute("user");
        if(user == null)
        {
            return "redirect:/toLogin" ;
        }
        QueryWrapper<Goodstable> wrapper = new QueryWrapper<>();
        wrapper.eq("boss_id",user.getUserId());
        // state为1代表上架
        wrapper.eq("state",1);
        wrapper.orderByDesc("id");
        PageInfo pageInfo = null;
        if(pageNum == null){
            Integer pageNum2 = (Integer)session.getAttribute("pageNum");
            if(pageNum2 == null)
            {
                pageInfo = getPageInfo(1, 4, wrapper);
            }else {
                pageInfo = getPageInfo(pageNum2, 4, wrapper);
                session.removeAttribute("pageNum");
            }

        }else {
            pageInfo = getPageInfo(pageNum, 4, wrapper);
        }

        model.addAttribute("pageInfo",pageInfo);
        return "user/seller_center_goods";
    }

    @Override
    public String toUpdateGoodIndex(Integer id,Model model,Integer pageNum,HttpSession session) {
        Goodstable goodstable = goodstableMapper.selectById(id);
        model.addAttribute("good",goodstable);
        List<Goodstype> goodstypes = goodstypeMapper.selectList(null);
        model.addAttribute("goodTypes",goodstypes);
        session.setAttribute("pageNum",pageNum);
        return "user/seller_center_update";
    }

    @Override
    public JSONResult<Void> updateGood(String name, String newPrice, String store, String goodDetail, Integer typeId
            ,Integer id,HttpSession session) {

        //检查商品名称
        JSONResult<Void> nameResutl = checkName(name);
        if(nameResutl.getCode() != 200)
        {
            return nameResutl;
        }
        //检查商品详情
        JSONResult<Void> goodDetail2 = checkGoodDetail(goodDetail);
        if(goodDetail2.getCode() != 200)
        {
            return goodDetail2;
        }
        //检查商品数量
        JSONResult<Void> goodNum = checkGoodNum(store);
        if(goodNum.getCode() != 200)
        {
            return goodNum;
        }
        //检查商品价格
        JSONResult<Void> goodPrice = checkGoodPrice(newPrice);
        if(goodPrice.getCode() != 200)
        {
            return goodPrice;
        }

        Goodstable goodstable = new Goodstable();
        goodstable.setName(name);
        goodstable.setOldPrice(Double.parseDouble(newPrice));
        goodstable.setNewPrice(Double.parseDouble(newPrice));
        goodstable.setStore(Integer.parseInt(store));
        if(picturePath != null){
            goodstable.setPicture(picturePath);
        }
        goodstable.setFlag(2);
        goodstable.setTypeId(typeId);
        goodstable.setModifyTime(new Date());
        goodstable.setState(1);
        goodstable.setGoodDetail(goodDetail);
        goodstable.setId(id);
        //商家id 默认为2，先写死
        User user = (User)session.getAttribute("user");
        if(user == null)
        {
            return new JSONResult<>(203,"请商家先登录");
        }
        goodstable.setBossId(user.getUserId());
        int insert = goodstableMapper.updateById(goodstable);
        if(insert != 1)
        {
            return new JSONResult<>(205,"更新失败");
        }
        picturePath = null;
        return new JSONResult<>(200,"更新成功");
    }

//    这里是更新商品状态为下架
    @Override
    public String deleteGoodById(Integer id,Integer pageNum) {
        Goodstable goodstable = goodstableMapper.selectById(id);
        //state 为2是下架
        goodstable.setState(2);
        goodstableMapper.updateById(goodstable);
        return "redirect:/toGoodsInfo?pageNum="+pageNum;
    }

    @Override
    public String batchDeleteGood(String goodIds) {
        String[] split = goodIds.split(",");
        ArrayList<Integer> list = new ArrayList<>();
        for (String s : split) {
            list.add(Integer.valueOf(s));
        }
        QueryWrapper<Goodstable> wrapper = new QueryWrapper<>();
        wrapper.in("id",list);
        Goodstable goodstable = new Goodstable();
        goodstable.setState(2);
        goodstableMapper.update(goodstable,wrapper);
        return "redirect:/toGoodsInfo";
    }




    //从商品详情页面按立即购买跳转到结算界面
    @Override
    public String settlement(Integer goodId, Model model,Integer num,HttpSession session
            ,Integer orderId,Integer addressStatus) {

        User user=(User)session.getAttribute("user");
        Integer Uid=user.getUserId();
        QueryWrapper queryWrapper=new QueryWrapper<Address>();
        queryWrapper.eq("user_id",Uid);
        queryWrapper.eq("flag",1);
        Address address= addressMapper.selectOne(queryWrapper);
        if(address==null){
            model.addAttribute("phone",null);
            model.addAttribute("addressInfo",null);
            model.addAttribute("addressId",null);
//            return "user/place_order";
        }
        else {
            String addressInfo = address.getAddress();
            String phone=address.getPhone();
            System.out.println("addressInfo:"+addressInfo);
            System.out.println("phone:"+phone);
            model.addAttribute("phone",phone);
            model.addAttribute("addressInfo",addressInfo);
            model.addAttribute("addressId",address.getId());
        }

        if(num != null && goodId != null && addressStatus == null)
        {
            Goodstable goodstable=goodstableMapper.selectById(goodId);
            goodstable.setStore(num);
            Ordertable ordertable = new Ordertable().setUserId(user.getUserId()).setPrice(goodstable.getNewPrice()*num)
                    .setStatus(1).setOrderDate(new Date());
            int insert = ordertableMapper.insert(ordertable);
            Orderdetail orderdetail = new Orderdetail().setGoodId(goodId).setNum(num).setOrdedetailId(ordertable.getId());
            int insert1 = orderdetailMapper.insert(orderdetail);
            model.addAttribute("goodstable",goodstable);
            model.addAttribute("orderId",ordertable.getId());
            return "user/place_order";
        }
        if(num != null && goodId != null && addressStatus != null)
        {
            Goodstable goodstable=goodstableMapper.selectById(goodId);
            goodstable.setStore(num);
            Integer id = ordertableMapper.getMaxOrderId();
            model.addAttribute("goodstable",goodstable);
            model.addAttribute("orderId",id);
            return "user/place_order";
        }
        Ordertable ordertable = ordertableMapper.selectById(orderId);
        //获取该订单中的订单详情的商品信息
        QueryWrapper<Orderdetail> wrapper = new QueryWrapper<>();
        wrapper.eq("ordedetail_id",orderId);
        List<Orderdetail> orderdetails = orderdetailMapper.selectList(wrapper);
        ArrayList<Integer> integers = new ArrayList<>();
        ArrayList<Goodstable> goodstables = new ArrayList<>();
        for (Orderdetail orderdetail : orderdetails) {
            Goodstable goodstable = goodstableMapper.selectById(orderdetail.getGoodId());
            goodstable.setStore(orderdetail.getNum());
            goodstables.add(goodstable);
        }
        model.addAttribute("goodstable",goodstables);
        model.addAttribute("orderId",orderId);
        session.setAttribute("carStatus",1);
        return "user/place_order";
    }

    @Override
    public PageInfo getPageInfo(Integer pageNum,Integer pageSize,QueryWrapper<Goodstable> queryWrapper)
    {
        PageHelper.startPage(pageNum,pageSize);
        List<Goodstable> list = goodstableMapper.selectList(queryWrapper);
        PageInfo<Goodstable> pageInfo = null;
        pageInfo = new PageInfo<>(list);
        if(pageInfo.getSize()==0)
        {
            PageHelper.startPage(pageNum-1,pageSize);
            List<Goodstable> goodstables = goodstableMapper.selectList(queryWrapper);
            pageInfo = new PageInfo<>(goodstables);
        }
        if(pageInfo.isIsFirstPage())
        {
            pageInfo.setPrePage(1);
        }
        if(pageInfo.isIsLastPage())
        {
            pageInfo.setNextPage(pageInfo.getPages());
        }
        return pageInfo;
    }
    //商家查看与自己店铺有关的查看订单详情
    @Override
    public String sellerQueryOrder(Model model, HttpSession session) {
        // 这里查出用户的id
        User user = (User)session.getAttribute("user");
        Integer userId = user.getUserId();
        // 这里还应该加上对用户的判断，如若用户为空，则要提醒
        // 调用sql语句查出相关数据
//        boss_id = "1";
        List<SellerOrder> sellerOrdersList = goodstableMapper.sellerQueryOrder(userId);
        model.addAttribute("sellerOrdersList",sellerOrdersList);
        return "/seller/seller_checkOrder";
    }

    //商家查看每种商品的详细购买情况
    @Override
    public String sellerOrderDetail(String goodId, Model model) {
        List<SellerOrderDetail> sellerOrderDetails = goodstableMapper.sellerQueryOrderDetail(goodId);
        model.addAttribute("OrderDetails",sellerOrderDetails);
        return "/seller/seller_orderDetail";
    }

    //商家查看全部评论，管理评论
    @Override
    public String queryComments(Model model,HttpSession session) {

        //获取用户的user 有可能为空
//        User user = (User)session.getAttribute("user");
//        if (user == null)
//            model.addAttribute("msg","登录超时，请重新登录");

        // 获取商户id
//        Integer userId = user.getUserId();

        // 获取评论列表
//        List<SellerComments> sellerComments = goodstableMapper.queryComments(userId);
        List<SellerComments> sellerComments = goodstableMapper.queryComments(1);


        //封装到model里面
        model.addAttribute("sellerComments",sellerComments);

        return "/seller/seller_comments";

    }
}
